package com.bsg.upm.service;

import java.text.MessageFormat;
import java.util.Map;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.constant.DictTypeConstants;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.constant.OperateDictTypeConstants;
import com.bsg.upm.constant.SysConstants;
import com.bsg.upm.dto.RgDto;
import com.bsg.upm.entity.SanEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;

/**
 * RG管理业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class RgService extends BaseService {

	/**
	 * 获取RG列表
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			// 结果集
			JSONArray results = new JSONArray();

			// SAN编码
			String sanId = (String) paramMap.get("sanId");

			// 获取指定的SAN
			SanEntity san = sanDao.get(sanId);
			if (san == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "SAN不存在");
			}

			// 站点
			String siteId = san.getSite().getId();

			// 从MGM获取SAN信息
			JSONObject mgmSanInfo = getSanInfoFromMGM(siteId, san.getRelateId());
			if (mgmSanInfo != null) {
				JSONArray rgsInfo = mgmSanInfo.getJSONArray("spaces");
				if (rgsInfo != null && rgsInfo.size() > 0) {
					for (int i = 0; i < rgsInfo.size(); i++) {
						JSONObject rgInfo = rgsInfo.getJSONObject(i);
						RgDto rgDto = buildShowDto(rgInfo);
						results.add(rgDto);
					}
				}
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("SAN查询异常", e);
			throw new APIException("SAN查询异常:" + e.getMessage());
		}
	}

	/**
	 * RG新增
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson save(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_ADD;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 保存RG信息
			saveRgToMGM(paramMap);

			// RG编码
			String code = (String) paramMap.get("code");
			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_RG, operateAcion, code, code);

			return RespJsonFactory.buildCreated();
		} catch (Exception e) {
			logger.error("RG" + operateAcionText + "异常", e);
			throw new APIException("RG" + operateAcionText + "异常");
		}
	}

	/**
	 * RG启用/停用
	 * 
	 * @param mgmRgId
	 *            rg编码
	 * @param enable
	 *            是否启用
	 * @param sanId
	 *            SAN编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson enable(String mgmRgId, boolean enable, String sanId) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_DISABLE;
		if (enable) {
			operateAcion = OperateDictConstants.ACTION_ENABLE;
		}
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定的SAN
			SanEntity san = sanDao.get(sanId);

			// 站点编码
			String siteId = san.getSite().getId();
			if (enable) {
				// RG启用
				enableRgToMGM(siteId, san.getRelateId(), mgmRgId);
			} else {
				// RG停用
				disableRgToMGM(siteId, san.getRelateId(), mgmRgId);
			}

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_RG, operateAcion, mgmRgId, mgmRgId);

			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("RG" + operateAcionText + "异常", e);
			throw new APIException("RG" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * RG删除
	 * 
	 * @param mgmRgId
	 *            MGM RG编码
	 * @param sanId
	 *            SAN编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson remove(String mgmRgId, String sanId) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_REMOVE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定的SAN
			SanEntity san = sanDao.get(sanId);

			// 站点
			String siteId = san.getSite().getId();

			// 从MGM删除RG信息
			removeRgFromMGM(siteId, san.getRelateId(), mgmRgId);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_RG, operateAcion, mgmRgId, mgmRgId);

			return RespJsonFactory.buildNoContent();
		} catch (Exception e) {
			logger.error("RG" + operateAcionText + "异常", e);
			throw new APIException("RG" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 从MGM获取SAN信息
	 * 
	 * @param siteId
	 *            站点编码
	 * @param mgmSanId
	 *            MGM SAN编码
	 * @return MGM SAN信息
	 * @throws APIException
	 *             API异常处理类
	 */
	private JSONObject getSanInfoFromMGM(String siteId, String mgmSanId) throws APIException {
		String urlPattern = "/{0}/storage/san/{1}";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, mgmSanId);
		RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_MGM, url);
		if (httpRespJson.getStatus() == HttpStatus.SC_OK) {
			return ((JSONObject) httpRespJson.getData());
		} else {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * 保存RG信息
	 * 
	 * @param paramMap
	 *            请求参数
	 * @throws APIException
	 *             API异常处理类
	 */
	private void saveRgToMGM(Map<String, Object> paramMap) throws APIException {
		String sanId = (String) paramMap.get("sanId");
		String code = (String) paramMap.get("code");
		SanEntity san = sanDao.get(sanId);
		String siteId = san.getSite().getId();

		String urlPattern = "/{0}/storage/san/{1}/raid_group/{2}";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, san.getRelateId(), code);
		RespJson httpRespJson = sendHttpPost(siteId, SysConstants.INTERFACE_TYPE_MGM, url, null);
		if (httpRespJson.getStatus() != HttpStatus.SC_CREATED) {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * RG启用
	 * 
	 * @param siteId
	 *            站点编码
	 * @param mgmSanId
	 *            MGM SAN编码
	 * @param mgmRgId
	 *            MGM RG编码
	 * @throws APIException
	 *             API异常处理类
	 */
	private void enableRgToMGM(String siteId, String mgmSanId, String mgmRgId) throws APIException {
		String urlPattern = "/{0}/storage/san/{1}/raid_group/{2}/enable";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, mgmSanId, mgmRgId);
		RespJson httpRespJson = sendHttpPut(siteId, SysConstants.INTERFACE_TYPE_MGM, url, null);
		if (httpRespJson.getStatus() != HttpStatus.SC_OK) {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * RG停用
	 * 
	 * @param siteId
	 *            站点编码
	 * @param mgmSanId
	 *            MGM SAN编码
	 * @param mgmRgId
	 *            MGM RG编码
	 * @throws APIException
	 *             API异常处理类
	 */
	private void disableRgToMGM(String siteId, String mgmSanId, String mgmRgId) throws APIException {
		String urlPattern = "/{0}/storage/san/{1}/raid_group/{2}/disable";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, mgmSanId, mgmRgId);
		RespJson httpRespJson = sendHttpPut(siteId, SysConstants.INTERFACE_TYPE_MGM, url, null);
		if (httpRespJson.getStatus() != HttpStatus.SC_OK) {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * 从MGM删除RG信息
	 * 
	 * @param siteId
	 *            站点编码
	 * @param mgmSanId
	 *            MGM SAN编码
	 * @param mgmRgId
	 *            MGM RG编码
	 * @throws APIException
	 *             API异常处理类
	 */
	private void removeRgFromMGM(String siteId, String mgmSanId, String mgmRgId) throws APIException {
		String urlPattern = "/{0}/storage/san/{1}/raid_group/{2}";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, mgmSanId, mgmRgId);
		RespJson httpRespJson = sendHttpDelete(siteId, SysConstants.INTERFACE_TYPE_MGM, url);
		if (httpRespJson.getStatus() != HttpStatus.SC_NO_CONTENT) {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * 构建RG展示对象
	 * 
	 * @param mgmRgInfo
	 *            MGM RG信息
	 * @return RG展示独享
	 */
	private RgDto buildShowDto(JSONObject mgmRgInfo) {
		RgDto rgDto = new RgDto();
		rgDto.setNumber(mgmRgInfo.getString("id"));
		rgDto.setTotal(mgmRgInfo.getLongValue("total"));
		rgDto.setFree(mgmRgInfo.getLongValue("free"));
		rgDto.setLunNum(mgmRgInfo.getInteger("lun_num"));
		rgDto.setEnabled(mgmRgInfo.getBoolean("enable"));
		rgDto.setEnabledText(dictTypeCache.getTextFromCache(DictTypeConstants.STATUS_ENABLED,
				String.valueOf(mgmRgInfo.getBoolean("enable"))));
		return rgDto;
	}
}
